import { getAuthority } from "@/utils/authority";

let lockReconnect = false;

const LinkWebsocket = (url: string, callback: (msg: any) => void) => {
  const c_token = getAuthority("dh-authority") || "";

  const createWs = () => {
    // ws://172.16.5.183:8000/fund/ws/${url}
    let ws_url = `ws:${location.host}/fund/ws/${url}`;
    const websocket = new WebSocket(ws_url, [c_token?.accessToken]);
    return websocket;
  };

  const initWs = (ws) => {
    let heartCheck = {
      timeout: 60000, //1分钟发一次心跳
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
      },
      start: function () {
        var self = this;
        this.timeoutObj = setTimeout(function () {
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          //onmessage拿到返回的心跳就说明连接正常
          ws.send("ping");
          console.log("ping!");
          self.serverTimeoutObj = setTimeout(function () {
            //如果超过一定时间还没重置，说明后端主动断开了
            ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
          }, self.timeout);
        }, this.timeout);
      },
    };

    ws.onopen = () => {
      console.log("websocket已打开");
      // ws.send('FOFTASK') // 不需要后端返回所有跑批结果，只要返回没完成的
      heartCheck.reset().start();
    };
    //发现消息进入
    ws.onmessage = (msg) => {
      console.log("websocket已连接");
      console.log(msg.data); // 第一次进去会显示：连接成功
      heartCheck.reset().start();
      if (msg.data !== "pong") {
        callback(msg.data);
      }
    };
    //关闭事件
    ws.onclose = function (e) {
      console.log("websocket已关闭");
      console.log(
        "websocket 断开: " + e.code + " " + e.reason + " " + e.wasClean,
      );
      reconnect();
    };
    //发生了错误事件
    ws.onerror = function () {
      console.log("websocket发生了错误");
      // reConnect()
      reconnect();
    };
  };

  const initConnect = () => {
    const ws = createWs();
    initWs(ws);
  };

  const reconnect = () => {
    if (lockReconnect) return;
    lockReconnect = true;
    setTimeout(() => {
      initConnect();
      lockReconnect = false;
    }, 2000);
  };

  if (typeof WebSocket == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  } else {
    console.log("您的浏览器支持WebSocket");
    initConnect();
  }
};

export default LinkWebsocket;
